<?php

class EntityDefinition extends DomObjDefinition implements IEntityDefinition
{

  /**
   *
   * @var array
   */
  protected $fields = array();

  /**
   *
   * @var mixed
   */
  protected $pk;

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/domain/api/IEntityDefinition#addField($name, $def)
   */
  public function addField($name, IFieldDefinition $def)
  {
    $this->fields[$name] = $def;

    if ($def->getPrimaryKey()) {
      $this->pk = $name;
    }
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/domain/api/IDomObjDefinition#factory()
   * @return IEntity
   */
  public function factory()
  {
    $class = $this->class;

    if (! class_exists($class)) {
      return new CustomEntity($class, $this);
    }

    return parent::factory();
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/domain/api/IEntityDefinition#getTable()
   */
  public function getTable()
  {
    return $this->getPkField()->getTable();
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/domain/api/IEntityDefinition#getField($name)
   */
  public function getField($name)
  {
    if (! $this->hasField($name)) {
      throw new FieldNotFoundException("Field not found in entity: <b>{$this->getClass()}.$name</b>");
    }

    return $this->fields[$name];
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/domain/api/IEntityDefinition#getFields()
   */
  public function getFields()
  {
    return $this->fields;
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/domain/api/IEntityDefinition#getPk()
   */
  public function getPk()
  {
    return $this->pk;
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/domain/api/IEntityDefinition#getPk()
   */
  public function getPkName()
  {
    return $this->getPkField()->getName();
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/domain/api/IEntityDefinition#getPkField()
   */
  public function getPkField()
  {
    return $this->getField($this->getPk());
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/domain/api/IEntityDefinition#hasField($name)
   */
  public function hasField($name)
  {
    return isset($this->fields[$name]);
  }

}

?>